package com.donger.auth;

import com.donger.common.security.filter.ValidateCodeFilter;
import com.donger.common.security.mobile.MobileSecurityConfigurer;
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * 资源服务器配置
 *
 * @author xyx
 */
@Configuration
//让客户端可以通过合法的令牌来获取资源。
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true)
@AllArgsConstructor
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    private final MobileSecurityConfigurer mobileSecurityConfigurer;

    private final ValidateCodeFilter validateCodeFilter;

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        super.configure(resources);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                // 添加验证码校验过滤器
                .addFilterAfter(validateCodeFilter, UsernamePasswordAuthenticationFilter.class)
                // 授权配置
                .authorizeRequests()
                // 无需认证的请求路径
                .antMatchers("/swagger-resources/**").permitAll()
                .antMatchers("/swagger-ui.html").permitAll()
                .antMatchers("/v2/api-docs").permitAll()
                .antMatchers("/swagger/api-docs").permitAll()
                .antMatchers("/webjars/**").permitAll()
                .antMatchers("/static/**").permitAll()
                .antMatchers("/oauth/**").permitAll()
                .antMatchers("/token/**").permitAll()
                .antMatchers("/mobile/*").permitAll()
                .antMatchers("/sys/mobile/*").permitAll()
                .antMatchers("/sys/user/captcha.jpg").permitAll()
                .antMatchers("/druid/**").permitAll()
                // 所有请求  都需要认证
                .anyRequest().authenticated()
            .and()
                .csrf().disable()
                .apply(mobileSecurityConfigurer);
    }
}
